package me.yuzho.study.concurrency.java8;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;


/** 使用Executor Service 来执行多线程任务
 * @author yzhou-citrix
 *
 */
public class Case2UseExecutor {

    public static void main(String[] args) {
        
        ExecutorService executor =  Executors.newSingleThreadExecutor();
        
        executor.submit(() -> {
            
            String threadName = Thread.currentThread().getName();
            System.out.println("Hello " + threadName);
        });
        
        /* you'll notice an important difference: 
            the java process never stops! Executors have to be stopped explicitly - 
            otherwise they keep listening for new tasks.
        */
        executor.shutdown();
        try {
            executor.awaitTermination(5, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        finally {
            if (!executor.isTerminated()) {
                System.err.println("cancel non-finished tasks");
            }
            executor.shutdownNow();
            System.out.println("shutdown finished");
        }
    }

}
